<template>
  <div>
    <a-form ref="formSearchRef" name="advanced_search" class="ant-advanced-search-form" :model="formSearchField">
      <a-row :gutter="24">
        <a-col :span="formSearchColSpan">
          <a-form-item name="phone" label="联系方式">
            <a-input v-model:value="formSearchField.phone" placeholder="请输入联系方式" style="width: 95%;" />
          </a-form-item>
        </a-col>
        <a-col :span="formSearchColSpan">
          <a-form-item name="language" label="语言">
            <a-select v-model:value="formSearchField.language" placeholder="请选择语言" style="width: 95%;">
              <a-select-option value="">全部</a-select-option>
              <a-select-option v-for="(item, index) in languageMap" :key="index" :value="index">{{ item
                }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="formSearchColSpan" v-show="formSearchExpand">
          <a-form-item name="status" label="状态">
            <a-select v-model:value="formSearchField.status" placeholder="请选择状态" style="width: 95%;">
              <a-select-option value="">全部</a-select-option>
              <a-select-option v-for="(item, index) in statusMap" :key="index" :value="index">{{ item
                }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="formSearchColSpan" v-show="formSearchExpand">
          <a-form-item label="提交日期">
            <a-space style="display: flex;" size="middle">
              <a-form-item name="add_date_start" style="margin-bottom: -24px;">
                <a-date-picker v-model:value="formSearchField.add_date_start" value-format="YYYY-MM-DD"
                  placeholder="开始日期" />
              </a-form-item>
              <a-form-item name="add_date_end" label="至" style="margin-bottom: -24px;">
                <a-date-picker v-model:value="formSearchField.add_date_end" value-format="YYYY-MM-DD"
                  placeholder="结束日期" />
              </a-form-item>
            </a-space>
          </a-form-item>
        </a-col>
        <a-col :span="formSearchColSpan">
          <a-button type="primary" html-type="submit" @click="doSearchForm">搜索</a-button>
          <a-button style="margin: 0 8px" @click="resetFormRef">重置</a-button>
          <a-button type="link" @click="formSearchExpandChg" v-if="!formSearchExpand">更多搜索</a-button>
          <a-button type="link" @click="formSearchExpandChg" v-if="formSearchExpand">收起</a-button>
        </a-col>
      </a-row>
    </a-form>
    <a-table bordered :data-source="dataListSource" :columns="dataListColumns" :loading="isLoading"
      @change="dataTableChange" rowKey="id" :pagination="tablePagination">
      <template #bodyCell="{ column, text, record, index }">
        <template v-if="column.dataIndex === 'status_text'">
          <span style="color: blue;" v-if="record.status === 1">{{ text }}</span>
          <span style="color: red;" v-if="record.status === 3">{{ text }}</span>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <a-tag color="blue" v-if="adminCheckOption('user', 'contact_me', 'detail')"
            @click="openDetailShow(record.id)" style="margin: 5px 7px 5px 0;">详情</a-tag>
          <a-tooltip color="blue" placement="leftTop">
            <template #title>
              <span>点击可录入回复记录</span>
            </template>
            <a-tag color="blue" v-if="adminCheckOption('user', 'contact_me', 'reply') && record.status === 1"
              @click="replyShowModal(record.id,index)" style="margin: 5px 7px 5px 0;">回复</a-tag>
          </a-tooltip>
          <a-tooltip color="blue" placement="leftTop">
            <template #title>
              <span>点击可再次录入回复记录</span>
            </template>
            <a-tag color="blue" v-if="adminCheckOption('user', 'contact_me', 'reply') && record.status === 2"
              @click="replyShowModal(record.id,index)" style="margin: 5px 7px 5px 0;">继续回复</a-tag>
          </a-tooltip>
          <a-popconfirm title="确认要关闭吗？此操作不可恢复。" @confirm="onChangeStatus(record.id, 3, index)"
            v-if="adminCheckOption('user', 'contact_me', 'close') && (record.status === 1 || record.status === 2)">
            <a-tooltip color="red" placement="rightTop">
              <template #title>
                <span>当前是正常状态，点击可关闭此数据，将不能录入回复记录。此操作不可恢复</span>
              </template>
              <a-tag color="green" style="margin: 5px 7px 5px 0;">关闭</a-tag>
            </a-tooltip>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    
    <!-- 输入回复内容弹窗 -->
    <a-modal v-model:open="replyIsShow" ok-text="确定" width="600px"
      title="请输入回复内容" @ok="onSaveReply" :confirm-loading="replySaveLoading">
      <a-textarea v-model:value="replySavePost.remark" placeholder="请输入回复内容" :rows="6" />
    </a-modal>
    <!-- 详情 -->
    <a-modal v-model:open="detailOpen" ok-text="关闭" :cancel-button-props="{ style: { display: 'none' } }" width="1200px"
      title="详情" @ok="openDetailHide">
      <DetailModal ref="detailModalRef" v-if="detailOpen" :detailId="detailId" />
    </a-modal>
  </div>
</template>

<script setup>
import { reactive, ref, inject, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue'
import { getContactMeList, chgContactMeStatus } from "@/api/admin"   //引入api
import DetailModal from './detail.vue';

const { adminCheckOption } = inject('adminCheckOption');  // 依赖注入--权限校验函数

const formSearchColSpan = ref(8);  // 搜索--每个搜索项暂用宽度（共24宽度）
const isLoading = ref(false);    // 控制loading
const formSearchExpand = ref(false);    // 搜索--是否展开更多
const dataListSource = ref([]); // 数据列表
const dataTotal = ref(0);    // 符合条件的数据总数
const formSearchRef = ref();  // 表单搜索,ref对象
const currentPage = ref(1);  // 当前页码
const pageSize = ref(10);      // 每页显示条数
const statusMap = reactive({
  1: '待回复',
  2: '已回复',
  3: '已关闭',
});  //状态映射
const languageMap = reactive({
  'zh-cn': '简体中文',
  'zh-hk': '繁体中文',
  'en-us': '英文',
});  //状态映射

// 表格分页
const tablePagination = computed(() => ({
  total: dataTotal.value,
  current: currentPage.value,
  pageSize: pageSize.value,
  showTotal: (total, range) => `第 ${range[0]} 至 ${range[1]} 条数据，共 ${total} 条数据`
}));
// 数据列表字段
const dataListColumns = [
  {
    title: '联系方式',
    dataIndex: 'phone',
  },
  {
    title: '语言',
    dataIndex: 'language_cn',
  },
  {
    title: '提交日期',
    dataIndex: 'add_date',
  },
  {
    title: '最近一次回复内容',
    dataIndex: 'remark_last',
    width:400,
    customCell: (value, record, index) => {
      return {
        style: {
          whiteSpace: 'pre-wrap', // 保持原样式，内容自动换行
          wordBreak: 'break-word',
          overflow: 'visible', // 内容超出也不隐藏
        },
      };
    },
  },
  {
    title: '状态',
    dataIndex: 'status_text',
    width: 80
  },
  {
    title: '操作',
    dataIndex: 'operation',
  },
];
// 表单搜索字段
const formSearchField = reactive({
  page: currentPage.value,  //当前页码（current的值改变后，这里的值不会跟着改变，需要手动赋值）
  limit: pageSize.value,  //每页条数（pageSize的值改变后，这里的值不会跟着改变，需要手动赋值）
  phone: '',
  language: null,
  status: null,
});

// 表单搜索方法
const doSearchForm = () => {
  currentPage.value = 1;
  getDataList();
};

// 获取接口数据列表
const getDataList = () => {
  isLoading.value = true;

  formSearchField.page = currentPage.value;  //当前页码（current的值改变后，这里的值不会跟着改变，需要手动赋值）
  formSearchField.limit = pageSize.value;  //每页条数（pageSize的值改变后，这里的值不会跟着改变，需要手动赋值）

  getContactMeList(formSearchField).then((res) => {
    isLoading.value = false;
    if (res === false) return;

    dataListSource.value = res.data;  //数据列表
    dataTotal.value = res.count;  //总条数

    message.success('获取成功');
  }).catch((rej) => {
    isLoading.value = false;
    message.error('失败：' + rej);
  });
};

// 重置表单搜索
const resetFormRef = () => {
  formSearchRef.value.resetFields();
  currentPage.value = 1;
  getDataList();
};

// 修改数据状态
const onChangeStatus = (id, newStatus, dataIndex) => {
  isLoading.value = true;

  // 提交的数据
  let chgData = {
    id: id,
    status: newStatus
  };

  chgContactMeStatus(chgData).then((res) => {
    isLoading.value = false;
    if (res === false) return;

    // 修改数据状态，用于展示修改后的数据
    dataListSource.value[dataIndex].status = newStatus;
    dataListSource.value[dataIndex].status_text = statusMap[newStatus];

    message.success('操作成功');
  }).catch((rej) => {
    isLoading.value = false;
    message.error('失败：' + rej);
  });
};

// 数据列表分页、排序、过滤
const dataTableChange = (pagination, filters, sorter) => {
  currentPage.value = pagination.current;
  getDataList();
};

// 搜索--展开/收起更多搜索项
const formSearchExpandChg = () => {
  formSearchExpand.value = !formSearchExpand.value;
};

const replyIsShow = ref(false);  // 输入回复内容弹窗
const replySaveLoading = ref(false);    // 保存，显示loading
const replyDataIndex = ref(-1);  // 回复数据索引
const replySavePost = reactive({
  id: 0,
  remark: '',
});  // 保存回复内容
// 保存回复内容
const onSaveReply = () => {
  if (replySavePost.remark === '') {
    message.error('请输入回复内容');
    return;
  }
  replySaveLoading.value = true;

  chgContactMeStatus(replySavePost).then((res) => {
    replySaveLoading.value = false;
    if (res === false) return;

    // 修改数据状态，用于展示修改后的数据
    let newStatus = 2;
    dataListSource.value[replyDataIndex.value].remark_last = replySavePost.remark;
    dataListSource.value[replyDataIndex.value].status = newStatus;
    dataListSource.value[replyDataIndex.value].status_text = statusMap[newStatus];

    message.success('回复成功');
    replyModalHide();
  }).catch((rej) => {
    replySaveLoading.value = false;
    message.error('失败：' + rej);
  });
};
// 显示回复内容弹窗
const replyShowModal = (id, dataIndex) => {
  replyIsShow.value = true;
  replyDataIndex.value = dataIndex;
  replySavePost.id = id;
  replySavePost.remark = '';
};
// 关闭回复内容弹窗
const replyModalHide = () => {
  replyIsShow.value = false;
  replySaveLoading.value = false;
  replyDataIndex.value = -1;
  replySavePost.id = 0;
  replySavePost.remark = '';
};


const detailOpen = ref(false);    // 打开详情
const detailId = ref(0);    // 详情数据
// 打开详情
const openDetailShow = (id) => {
  detailId.value = id;
  detailOpen.value = true;
};

const openDetailHide = e => {
  detailOpen.value = false;
};

// 页面加载完成后，获取数据列表
onMounted(() => {
  getDataList();
})
</script>

<style scoped></style>